package com.minelx.sqlstructures.statements.parse.select.where;

import com.minelx.sequence.core.Match;
import com.minelx.sequence.core.ReturnMatcher;
import com.minelx.sequence.core.StringScanner;
import com.minelx.sqlstructures.common.parse.JoinMatcher;
import com.minelx.sqlstructures.statements.clause.Sql;
import com.minelx.sqlstructures.statements.clause.Conditions;

import java.util.List;

import static java.util.stream.Collectors.toList;

public class InMatcher implements ReturnMatcher<Sql, StringScanner> {
	private static final String COMMA = ", ";

	private final JoinMatcher<String> valuesMatcher;

	public InMatcher() {
		valuesMatcher = new JoinMatcher<>(Match.content(", "), new ValuesMatcher());
	}

	@Override
	public boolean isMatch(StringScanner source) {
		StringScanner copy = source.copy();
		copy.nextPage();
		copy.trim();
		return copy.exists("IN");
	}

	@Override
	public Sql onMatched(StringScanner source) {
		String left = source.nextPage();
		source.trim();
		source.goes("IN");
		source.trim();
		source.goes("(");
		List<String> values = source.stream(valuesMatcher).collect(toList());
		source.goes(")");
		return Conditions.in(left, String.join(COMMA, values));
	}
}
